package org.footballmanager.pandafootball.system.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.system.dao.FootRankDao;
import org.footballmanager.pandafootball.system.domain.FootQd;
import org.footballmanager.pandafootball.system.domain.FootRank;
import org.footballmanager.pandafootball.system.domain.FootTeam;
import org.footballmanager.pandafootball.system.domain.FootUser;
import org.footballmanager.pandafootball.system.form.impl.FootRankSearchForm;
import org.footballmanager.pandafootball.system.mapper.FootRankMapper;
import org.footballmanager.pandafootball.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class FootRankServiceImpl extends RepeatServiceImpl<FootRank> implements FootRankService {
    private static final double TOP1 = 30d;
    private static final double TOP2 = 20d;
    private static final double TOP3 = 10d;

    @Autowired
    private FootRankMapper footRankMapper;
    @Autowired
    private FootRankDao footRankDao;
    @Autowired
    private FootUserService footUserService;
    @Autowired
    private FootTeamService footTeamService;
    @Autowired
    private FootSjService footSjService;
    @Autowired
    private FootZnxService footZnxService;
    @Autowired
    private FootZjService footZjService;

    /**
     * 获取排位赛积分榜
     *
     * @return 排位赛积分榜
     */
    @Override
    public List<FootRank> getScoreboard() {
        Example example = new Example(FootRank.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("sj", footSjService.getSj());
        criteria.andEqualTo("delFlag", 0);
        example.orderBy("jf").desc().orderBy("jsq").desc().orderBy("jq").desc().orderBy("s").desc()
                .orderBy("p").desc().orderBy("f").desc();
        List<FootRank> list = findall(example);
        if (list != null && !list.isEmpty()) {
            return list;
        } else {
            return Collections.emptyList();
        }
    }

    /**
     * 根据用户主键获取记录
     *
     * @param userId 用户主键
     * @return 记录
     */
    @Override
    public FootRank findByUserid(Long userId) {
        Example example = new Example(FootRank.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("sj", footSjService.getSj());
        criteria.andEqualTo(Constants.USERID, userId);
        criteria.andEqualTo("delFlag", 0);
        FootRank ft = this.findByExample(example);
        if (ft != null) {
            return ft;
        }
        return null;
    }

    /**
     * 重新计算排名
     *
     * @param request 请求
     */
    @Transactional
    @Override
    public void reComputeRanking(HttpServletRequest request) {
        List<FootRank> list = this.getScoreboard();
        if (null != list && !list.isEmpty()) {
            int i = 1;
            for (FootRank fc : list) {
                fc.setPm(i++);
                if (request != null) {
                    fc.setUpdateId((Long) request.getSession().getAttribute(Constants.USERID));
                } else {
                    fc.setUpdateId(1L);
                }
                fc.setUpdateTime(new Date());
                footRankDao.updateByPrimaryKeySelective(fc);
            }
        }
    }

    /**
     * 根据用户主键查找对应所有的排位赛信息
     *
     * @param userId 用户主键
     * @return 排位赛信息
     */
    @Override
    public List<FootRank> getRanksByUserid(Long userId) {
        Example example = new Example(FootRank.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(Constants.USERID, userId);
        criteria.andEqualTo("delFlag", 0);
        return this.findall(example);
    }

    /**
     * 添加新的排位赛到数据库
     *
     * @param user    用户
     * @param qdId    球队主键
     * @param request 请求
     */
    @Override
    public void saveNewRank(FootUser user, Long qdId, HttpServletRequest request) {
        FootRank fc = new FootRank();
        fc.setQdId(qdId);
        fc.setBscc(0);
        fc.setS(0);
        fc.setF(0);
        fc.setP(0);
        fc.setSl(0D);
        fc.setSq(0);
        fc.setJf(0);
        fc.setJq(0);
        fc.setJsq(0);
        fc.setUserId(user.getId());
        fc.setUserName(user.getNike());
        fc.setSj(footSjService.getSj());
        this.save(fc, request);
    }

    /**
     * 更新排位赛的球队名称
     *
     * @param userId  用户主键
     * @param qd      球队实体类
     * @param request 请求
     */
    @Override
    public void updateRankQdName(Long userId, FootQd qd, HttpServletRequest request) {
        FootRank rank = this.findByUserid(userId);
        if (null != rank) {
            rank.setQdName(qd.getQdmc());
            this.updateNotNull(rank, request);
        }
    }

    /**
     * 发放排位赛的奖励
     *
     * @param request 请求
     */
    @Override
    public void reward(HttpServletRequest request) {
        List<FootRank> list = this.getScoreboard();
        if (!list.isEmpty()) {
            //第一名
            FootRank rank1 = list.get(0);
            if (null != rank1) {
                this.rewardTop3(rank1, "一", request);
            }
        }
        if (list.size() > 1) {
            //第二名
            FootRank rank2 = list.get(1);
            if (null != rank2) {
                this.rewardTop3(rank2, "二", request);
            }
        }
        if (list.size() > 2) {
            //第三名
            FootRank rank3 = list.get(2);
            if (null != rank3) {
                this.rewardTop3(rank3, "三", request);
            }
        }
    }

    /**
     * 处理第三名奖励
     *
     * @param rank    排位实体列
     * @param top     汉子top
     * @param request 请求
     */
    private void rewardTop3(FootRank rank, String top, HttpServletRequest request) {
        if (rank != null) {
            FootTeam team = footTeamService.getTeamByUserid(rank.getUserId());
            double money = 0D;
            switch (top) {
                case "一":
                    money = TOP1;
                    break;
                case "二":
                    money = TOP2;
                    break;
                case "三":
                    money = TOP3;
                    break;
                default:
                    break;
            }
            team.setQdZzj(team.getQdZzj() + money);
            String result = "恭喜您,获得排位赛第" + top + "名,发放奖金:" +
                    new DecimalFormat(",###").format(money) + "PB,当前总资金为:" +
                    new DecimalFormat(",###").format(team.getQdZzj()) + "PB";
            team.setYy(result);
            footTeamService.updateNotNull(team, request);
        }
    }

    /**
     * 查找是否有重复数据
     *
     * @param newrank 新的排位实体
     * @return 是否有重复
     */
    @Override
    public boolean findRepeatData(FootRank newrank) {
        Example example = new Example(FootRank.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("qdId", newrank.getQdId());
        criteria.andEqualTo(Constants.USERID, newrank.getUserId());
        criteria.andEqualTo("sj", newrank.getSj());
        criteria.andEqualTo("delFlag", 0);
        List<FootRank> list = this.findall(example);
        return null != list && !list.isEmpty();
    }

    /**
     * 翻页方法
     *
     * @param footRankSearchForm 条件
     * @return 列表
     */
    @Override
    public List<FootRank> findall(FootRankSearchForm footRankSearchForm) {
        return footRankMapper.findall(footRankSearchForm);
    }

    /**
     * 根据主键获取记录
     *
     * @param id 主键
     * @return 记录
     */
    @Override
    public FootRank get(Serializable id) {
        return footRankMapper.findById(id);
    }

    /**
     * 查询
     *
     * @param entityname         实体类名
     * @param map                参数
     * @param footRankSearchForm 条件
     */
    @Override
    public void search(String entityname, Model map, FootRankSearchForm footRankSearchForm) {
        map.addAttribute(String.format(Constants.FORMNAME, entityname), footRankSearchForm);
        Page<FootRank> page = PageHelper.startPage(footRankSearchForm.getPageIndex(), footRankSearchForm.getPageSize());
        List<FootRank> list = this.findall(footRankSearchForm);
        map.addAttribute(Constants.PI, page.toPageInfo());
        map.addAttribute(String.format(Constants.LISTENTITY, entityname), list);
    }

    /**
     * 补全本赛季没有加入的玩家
     *
     * @param sjId 赛季主键
     */
    @Override
    public void processFixBySj(Long sjId) {
        List<FootUser> list = footUserService.getAllWithoutAdmin(null);
        if (list == null || list.isEmpty()) {
            return;
        }
        for (FootUser footUser : list) {
            FootRank rank = findByUserIdAndSj(footUser.getId(), sjId);
            if (rank == null && footUser.getJoins()) {
                FootRank oldRank = findByUserIdAndSj(footUser.getId(), footSjService.getLastSj());
                if (oldRank != null) {
                    FootRank newRank = new FootRank();
                    BeanUtils.copyProperties(oldRank, newRank);
                    newRank.setId(null);
                    newRank.setSj(sjId);
                    this.save(newRank, null);
                } else {
                    this.saveNewRank(footUser, null, null);
                }
            }
        }
    }

    /**
     * 根据用户主键和赛季主键查询排位赛记录
     *
     * @param userId 用户主键
     * @param sjId   赛季主键
     * @return 排位赛记录
     */
    private FootRank findByUserIdAndSj(Long userId, Long sjId) {
        Example example = new Example(FootRank.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        criteria.andEqualTo("sj", sjId);
        criteria.andEqualTo("delFlag", 0);
        return this.findByExample(example);
    }

    /**
     * 根据用户主键删除对应记录
     *
     * @param userId  用户主键
     * @param request 请求
     */
    @Override
    public void deleteByUserId(Long userId, HttpServletRequest request) {
        //删除rank信息
        List<FootRank> rankList = this.getRanksByUserid(userId);
        if (rankList != null && !rankList.isEmpty()) {
            for (FootRank fr : rankList) {
                this.delete(fr.getId(), request);
            }
        }
    }
}
